package com.example.utils;

import com.example.circuit.CircuitSignalParsing;

import java.util.Queue;

public class Utils {

    /**
     * 时延单位，用于提升性能，单位毫秒
     */
    public static int TimeDelay = 10;

    /**
     * String转为电信号保存在queue中
     * @param string
     * @param queue
     * @param CSP
     */
    public static void setQueue(String string, Queue<Byte> queue, CircuitSignalParsing CSP){
        byte[] bytes = strToByteArr(string);
        for (byte b:bytes){
            CSP.code(queue,b);
        }
    }

    /**
     * bite流转String
     * @param queue
     * @return
     */
    public static String getString(Queue<Byte> queue){
        int length = queue.size();
        byte[] bytes = new byte[length];
        for (int i = 0;i<length;i++){
            bytes[i] = queue.poll();
        }
        return byteArrToStr(bytes);
    }
    public static String byteArrToStr(byte[] bytes){
        StringBuilder result = new StringBuilder();
        int sum = 0;
        char c;
        for (int i = 0;i<bytes.length;i++){
            sum +=bytes[i]<<(7-i%8);
            if (i%8==7){
                c = (char) sum;
                result.append(c);
                sum = 0;
            }
        }
        return result.toString();
    }
    public static byte[] strToByteArr(String string){
        byte[] bytes= new byte[string.length()*8];
        int i = 0;
        for (char c:StrToBinStr(string).toCharArray()){
            bytes[i] = (byte) (c-'0');
            i++;
        }
        return bytes;
    }

    private static String StrToBinStr(String string1) {
        StringBuilder result= new StringBuilder();
        for (char c : string1.toCharArray()) {
            StringBuilder string2 = new StringBuilder(Integer.toBinaryString(c));
            while (string2.length()<8){
                string2.insert(0, "0");}
            result.append(string2);
        }
        return result.toString();
    }

}
